package com.yhxd.modular.system.api;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.yhxd.modular.news.entity.Classify;
import com.yhxd.modular.news.entity.News;
import com.yhxd.modular.news.entity.QNews;
import com.yhxd.modular.news.service.AllInformationService;
import com.yhxd.modular.news.service.ClassifyService;
import com.yhxd.modular.reference.entity.PublicFile;
import com.yhxd.modular.reference.entity.QPublicFile;
import com.yhxd.modular.reference.service.PublicFileService;
import com.yhxd.modular.system.vo.ResultVo;
import io.swagger.annotations.Api;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping(value = "/api/user")
@Api
public class ApiUserController {

    @Autowired
    private AllInformationService allInformationService;
    @Autowired
    private ClassifyService classifyService;
    @Autowired
    private PublicFileService publicFileService;

    @GetMapping(value = "/login")
    public String login() {
        return "web/pages/login";
    }

    @GetMapping(value = "/index")
    public String list(Model model) {
        Object primaryPrincipal = SecurityUtils.getSubject().getPrincipals();
        if(primaryPrincipal!=null){
            model.addAttribute("loginState",1);
        }else{
            model.addAttribute("loginState",0);
        }
        this.findClassify(model,null,null);
        //中心动态
        this.listNews(model,1,8,5l,"centers");
        //最新发布
        this.listNews(model,1,5,null,"newests");
        //工作简报
        this.listNews(model,1,5,11l,"works");
        //通知公告
        this.listNews(model,1,5,7l,"ads");
        //深圳不动产
        this.listNews(model,1,5,9l,"reals");
        List<Classify> classify = (List<Classify>) model.getAttribute("classify");
        model.addAttribute("centersClass",classify.stream().filter((Classify c) -> c.getId() == 5l).findFirst().orElse(null).getClassifys().get(0));
        model.addAttribute("worksClass",classify.stream().filter((Classify c) -> c.getId() == 11l).findFirst().orElse(null).getClassifys().get(0));
        model.addAttribute("adsClass",classify.stream().filter((Classify c) -> c.getId() == 7l).findFirst().orElse(null).getClassifys().get(0));
        model.addAttribute("realsClass",classify.stream().filter((Classify c) -> c.getId() == 9l).findFirst().orElse(null).getClassifys().get(0));

        return "web/index";
    }

    public void listNews(Model model,Integer page, Integer limit,Long classifyId,String key){
        News news = new News(1);
        news.setParentClassify(new Classify(classifyId));
        QPageRequest pageRequest = QPageRequest.of(page - 1, limit, new OrderSpecifier(Order.DESC, QNews.news.publishDate));
        Page<News> resourcePage = this.allInformationService.findPageNews(pageRequest,news);
        switch (key){
            case "centers":
                model.addAttribute("centers",resourcePage.getContent());
                break;
            case "newests":
                model.addAttribute("newests",resourcePage.getContent());
                break;
            case "works":
                model.addAttribute("works",resourcePage.getContent());
                break;
            case "ads":
                model.addAttribute("ads",resourcePage.getContent());
                break;
            case "reals":
                model.addAttribute("reals",resourcePage.getContent());
                break;
        }
    }

    public void findClassify(Model model,Long pid,Long id){
        //前端分类
       /* Object classify= RedissonUtils.getObject("classify");
        if(classify!=null) {
            List<Classify> cs =(List<Classify>)classify;
            model.addAttribute("classify", cs);
            if(CollectionUtils.isNotEmpty(cs) && pid != null){
                Optional<Classify> first = cs.stream().filter((Classify c) -> c.getPid() == pid).findFirst();
                Classify classify = first.orElse(null);
                model.addAttribute("childs",classify.getClassifys());
            }
        }else{*/
            //获取所有的分类
            List<Classify> cs = classifyService.findClassify(null, 0);
            model.addAttribute("classify", cs);
            if(CollectionUtils.isNotEmpty(cs) && pid != null){
                //获取父类
                Optional<Classify> first1 = cs.stream().filter((Classify c) -> c.getId() == pid).findFirst();
                Classify classify = first1.orElse(null);
                if(classify!=null){
                    model.addAttribute("pclass", classify);
                    //文档类型
                    model.addAttribute("type",classify.getType());
                    List<Classify> classifys = classify.getClassifys();
                    if(CollectionUtils.isNotEmpty(classifys)) {
                        if (id != null) {
                            Optional<Classify> first2 = classifys.stream().filter((Classify c) -> c.getId() == id).findFirst();
                            model.addAttribute("cclass", first2.get());
                        }else{
                            model.addAttribute("cclass", classifys.get(0));
                        }
                        model.addAttribute("childs",classifys);
                    }else{
                        model.addAttribute("childs",new ArrayList<>());
                    }
                }
            }
            /*RedissonUtils.putObject("classify", classify);
        }*/
    }

    /**
     * 页面跳转
     * @return
     */
    @GetMapping(value = "/{url}")
    public String pages(Model model,@PathVariable("url") String url,Long pid,Long id,Integer page,Integer limit,Long contId) {
        if(url.indexOf("szfdc_it_wok.html")!=-1){
            return "web/pages/"+url;
        }
        News news=null;
        this.findClassify(model,pid,id);
        Integer type = Integer.valueOf(model.getAttribute("type").toString());
        if(type==1 && id!=null){
            news = new News(1);
            news.setChildClassify(new Classify(id));
            QPageRequest pageRequest = QPageRequest.of(0, 1, new OrderSpecifier(Order.DESC, QNews.news.publishDate));
            Page<News> resourcePage = this.allInformationService.findAll(pageRequest, news);
            //中心动态
            List<News> content = resourcePage.getContent();
            if(CollectionUtils.isNotEmpty(content)){
                news = content.get(0) ;
                model.addAttribute("news",news);
            }else{
                news = null ;
                model.addAttribute("news",news);
            }
        }
        if(contId!=null){
            news = this.allInformationService.findById(contId);
            model.addAttribute("news",news);
        }
        if(news != null && 1 == news.getConType()){
            url="center_content_pdf.html";
        }
        return "web/pages/"+url;
    }

    /**
     * 查询列表数据
     * @param page
     * @param limit
     * @return
     */
    @PostMapping(value = "/news")
    @ResponseBody
    public ResultVo findList(Integer page, Integer limit,Long id) {
        if(id == 19l){
            try {
                QPageRequest pageRequest = QPageRequest.of(page - 1, limit, new OrderSpecifier(Order.DESC, QPublicFile.publicFile.id));
                Page<PublicFile> filePage = this.publicFileService.findAll(pageRequest, null, null, null, null);
                return ResultVo.success(filePage);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultVo.error(e.getMessage());
            }
        }else {
            try {
                PageRequest pageRequest = PageRequest.of(page - 1, limit, Sort.Direction.DESC, "publishDate");
                Page<News> resourcePage = this.allInformationService.findAll(pageRequest, id);
                return ResultVo.success(resourcePage);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultVo.error(e.getMessage());
            }
        }
    }
}
